package com.ds.lens.data.service.dao;

import com.ds.lens.data.service.dao.entity.LensScheduleMonitorRelation;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface LensScheduleMonitorRelationDao {

    String COLUMNS = " id, schedule_id, monitor_id ";

    @Delete({
            "delete from lens_schedule_monitor_relation where schedule_id = #{scheduleId}"
    })
    int deleteByScheduleId(@Param("scheduleId") Long scheduleId);


    @Insert({"<script>", "insert into lens_schedule_monitor_relation (monitor_id, schedule_id)", "values ",
            "<foreach collection='records' item='record' separator=','>",
            "(#{record.monitorId},#{record.scheduleId})",
            "</foreach>", "</script>"})
    Long batchInsert(@Param("records") List<LensScheduleMonitorRelation> records);

    @Select({
            "select",
            COLUMNS,
            "from lens_schedule_monitor_relation",
            "where schedule_id = #{scheduleId}"
    })
    @ResultMap("scheduleMonitorRelation")
    List<LensScheduleMonitorRelation> selectByScheduleId(@Param("scheduleId") Long scheduleId);

    @Select({
            "<script>",
            "select",
            " b.schedule_id as schedule_id, b.monitor_id as monitor_id, a.end_time as end_time",
            "from lens_schedule_downtime a left join lens_schedule_monitor_relation b on a.id = b.schedule_id ",
            "where a.is_delete = 0 and a.state = 2 and b.monitor_id in ",
            "<foreach collection='monitorIds' item='monitorId' separator=',' open='(' close=')' >",
            "#{monitorId}",
            "</foreach>",
            "</script>"
    })
    @Results(id = "scheduleMonitorRelation", value = {
            @Result(column = "id", property = "id", jdbcType = JdbcType.BIGINT, id = true),
            @Result(column = "schedule_id", property = "scheduleId", jdbcType = JdbcType.BIGINT),
            @Result(column = "monitor_id", property = "monitorId", jdbcType = JdbcType.BIGINT),
            @Result(column = "end_time", property = "endTime", jdbcType = JdbcType.TIMESTAMP),
    })
    List<LensScheduleMonitorRelation> selectByMonitorId(@Param("monitorIds") List<Long> monitorIds);

}
